import Taro, { useShareAppMessage } from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
import IconFont from '@/assets/Iconfont';
import { demandListStore } from '@/business/store/demand/demandList';
import { searchStore } from '@/business/store/search/search';
import { demandDetailStore } from '@/business/store/demand/demandDetail';
import cssModule from './index.module.scss';
import { userDetailStore } from '@/business/store/user/userDetail';
import { myColletionStore } from '@/business/store/myColletion';

/**
 * @description 卡片底部操作栏
 * @author zhongze
 */

// 定义 demandDetail 的接口（可选，但推荐）
interface DemandDetail {
  id: string;
  isLiked: boolean;
  isDisliked: boolean;
  viewCount: number;
  likeCount: number;
  dislikeCount: number;
  collect: boolean;
  collectCount: number;
  title?: string;
  // 添加其他必要属性
}

// 组件接收的参数
interface DefaultPageProps {
  demandDetail: DemandDetail;
  cityCode?: string; // 城市编码
  source?: string;
}

export default function MainCardBar({ demandDetail, cityCode, source }: DefaultPageProps) {

  // 去举报
  const handleReport = (e: any) => {
    e.stopPropagation();
    Taro.navigateTo({
      url: `/subPackages/report/index?id=${demandDetail.id}&cityCode=${cityCode}`,
    });
  };

  // 用户操作（点赞、取消点赞、收藏、取消收藏）
  const handleOprate = async (e: any, demandDetail: DemandDetail, type: 'LIKE' | 'DISLIKE' | 'COLLECT') => {
    e.stopPropagation();
    try {
      console.log('detail', type)
      // 点赞、点踩
      const isAlreadyActive = (type === 'LIKE' && demandDetail.isLiked) || (type === 'DISLIKE' && demandDetail.isDisliked);
      const status = isAlreadyActive ? 'CANCEL' : 'VALID';
      const action = isAlreadyActive ? 'handleCancelLikeOrDislike' : 'handleLikeOrDislike';
      const demandId = demandDetailStore.getState().demandDetail.id;

      const currentStore = source === 'search' ? searchStore : source === 'user' ? userDetailStore : source === 'collection' ? myColletionStore : demandId ? demandDetailStore : demandListStore;

      if (type === 'LIKE' || type === 'DISLIKE') {
        if (source === 'search') {
          searchStore.getState()[action](demandDetail.id, type, status)
        } else if (source === 'user') {
          userDetailStore.getState()[action](demandDetail.id, type, status)
        } else if (source === 'collection') {
          myColletionStore.getState()[action](demandDetail.id, type, status)
        } else if (!demandId) {
          await demandListStore.getState()[action](demandDetail.id, type, status);
        } else {
          await demandDetailStore.getState()[action](demandDetail.id, type, status);
        }
      } else {

        // 收藏、取消收藏
        const isCollectActive = (
          type === 'COLLECT' && demandDetail.collect
        )
        if (isCollectActive) {
          await currentStore.getState().handleCancelCollect(demandDetail.id);
        } else {
          await currentStore.getState().handleCollect(demandDetail.id, 'collection', 'VALID');
        }
      }

    } catch (error) {
      console.error('操作失败:', error);
      Taro.showToast({
        title: '操作失败，请重试',
        icon: 'none',
      });
    }
  };

  // 微信分享
  // const handleWxShare = (e: any) => {
  //   e.stopPropagation();
  //   if (process.env.TARO_ENV === 'weapp') {
  //     Taro.showShareMenu({
  //       withShareTicket: true,
  //     });
  //   } else {
  //     Taro.showToast({
  //       title: '当前环境不支持分享功能',
  //       icon: 'none',
  //     });
  //   }
  // };
  useShareAppMessage((res) => {
    return {
      title: demandDetail.title,
      path: `subPackages/detail/index?id=${demandDetail.id}`
    }
  })

  return (
    <>
      <View className={cssModule.divider} />
      <View className={cssModule.container}>
        <View className={cssModule.eye}>
          <IconFont name='eye' size={32} />
          <Text className={cssModule.iconText}>{demandDetail.viewCount}次</Text>
        </View>
        <View className={cssModule.operate}>
          <Button className={cssModule.iconBox} onClick={handleReport}>
            <IconFont name='jubao' size={32} />
            <Text className={cssModule.iconText}>举报</Text>
          </Button>
          <Button className={cssModule.iconBox} openType="share">
            <IconFont name='share' size={32} />
            <Text className={cssModule.iconText}>分享</Text>
          </Button>
          <Button className={cssModule.iconBox} onClick={(e) => handleOprate(e, demandDetail, 'COLLECT')}>
            <IconFont name={demandDetail.collect ? 'weishoucang-copy' : 'weishoucang'} size={32} />
            <Text className={cssModule.iconText}>{demandDetail.collectCount}</Text>
          </Button>
          <Button className={cssModule.iconBox} onClick={(e) => handleOprate(e, demandDetail, 'LIKE')}>
            <IconFont name={demandDetail.isLiked ? 'like-copy' : 'like'} size={36} />
            <Text className={cssModule.iconText}>{demandDetail.likeCount}</Text>
          </Button>
          <Button className={cssModule.iconBox} onClick={(e) => handleOprate(e, demandDetail, 'DISLIKE')}>
            <IconFont name={demandDetail.isDisliked ? 'nolike-copy' : 'nolike'} size={36} />
            <Text className={cssModule.iconText}>{demandDetail.dislikeCount}</Text>
          </Button>
        </View>
      </View >
    </>
  );
}
